package sealte.wdgf.system.config;

import java.io.File;
import java.util.List;

import org.jdom2.Element;

import sealte.wdgf.model.system.DataSourceObject;
import sealte.wdgf.utils.XMLBaseObject;

public class DatabaseInfoReader {
	
	private Element dbInfo;
	private String driverClassName;
	private String url;
	private String userName;
	private String password;
	private int maxActive;
	private int minIdle;
	private int initialSize;
	
	public DatabaseInfoReader(){
		getDBInfo();
		this.driverClassName = dbInfo.getChildText("driver-class-name");
		this.url = dbInfo.getChildText("url");
		this.userName = dbInfo.getChildText("username");
		this.password = dbInfo.getChildText("password");
		this.maxActive = getIntValue(dbInfo.getChildText("max-active"));
		this.minIdle = getIntValue(dbInfo.getChildText("min-idle"));
		this.initialSize = getIntValue(dbInfo.getChildText("initial-size"));
	}
	
	private void getDBInfo(){
		XMLBaseObject xml = new XMLBaseObject(
				new File(DatabaseInfoReader.class.getResource("").getPath()
						+"../../../../../config/database-info.xml"));
		Element root = xml.getRoot();
		List<Element> dbInfoList = root.getChildren();
		for(Element ele:dbInfoList){
			if(ele.getAttributeValue("use").equals("true")){
				dbInfo = ele;
				break;
			}
		}
	}
	
	private int getIntValue(String strValue){
		if(null==strValue || strValue.trim().length()==0){
			return 0;
		}else{
			return Integer.valueOf(strValue);
		}
	}
		 
	public DataSourceObject getDataSourceObject(){
		 DataSourceObject dso = new DataSourceObject();
		 dso.setDriverClassName(this.driverClassName);
		 dso.setUrl(this.url);
		 dso.setUserName(this.userName);
		 dso.setPassword(this.password);
		 dso.setMaxActive(this.maxActive);
		 dso.setMinIdle(this.minIdle);
		 dso.setInitialSize(this.initialSize);
		 return dso;
	}
}
